//
//  MyJobsViewController.m
//  MagicZhao
//
//  Created by hy002 on 2017/12/12.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "MyJobsViewController.h"
#import "JobsModel.h"
#import "ScoringModel.h"
#import "JobSetUpViewController.h"
#import "SetUpTimeViewController.h"
#import "CDZStarsControl.h"
#import "JobDetailViewController.h"
#import "FeedBackViewController.h"

static NSString *leftCellPath = @"ordercell";
static NSString *rightCellPath = @"scoringcell";
@interface MyJobsViewController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,CDZStarsControlDelegate>
@property (nonatomic, strong)UILabel *orderLab;
@property (nonatomic, strong)UILabel *scoringLab;
@property (nonatomic, strong)UIScrollView *scrollView;
@property (nonatomic, strong)UITableView *leftTableview;
@property (nonatomic, strong)UITableView *rightTableview;
@property (nonatomic, assign)NSInteger closeType;
@property (nonatomic, assign)NSInteger leftPage;
@property (nonatomic, assign)NSInteger rightPage;
@property (nonatomic, strong)NSMutableArray *orderAry;
@property (nonatomic, strong)NSMutableArray *scoringAry;

@end

@implementation MyJobsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _closeType = 0;
    _leftPage = 0;
    _rightPage = 0;
    _orderAry = [NSMutableArray arrayWithCapacity:0];
    _scoringAry = [NSMutableArray arrayWithCapacity:0];
    [self creatUI];
    [self requestProjectList:_leftPage];
    [self requestEvaluateList:_rightPage];
}

- (void)creatUI
{
    self.navigationItem.title = @"我的项目";
    self.view.backgroundColor = BacksColor;
    self.navigationController.navigationBar.translucent = NO;
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60*displaywidth)];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    UIView *lineAview = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-0.5*displaywidth, 0, 1*displaywidth, 60*displaywidth)];
    lineAview.backgroundColor = RGB(204, 204, 204);
    [topView addSubview:lineAview];
    NSArray *imgAry = @[@"xiangmudingdan",@"pingfenzan"];
    NSArray *titAry = @[@" 项目订单",@" 评价分数"];
    for (int i = 0; i < imgAry.count; i++)
    {
        UIButton *showBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2*i, 0, SCREEN_WIDTH/2, 35*displaywidth) ImageName:imgAry[i] Target:self Action:nil Title:titAry[i] Font:14.0];
        showBtn.backgroundColor = [UIColor clearColor];
        [showBtn setTitleColor:RGB(77, 77, 77) forState:UIControlStateNormal];
        [topView addSubview:showBtn];
        UILabel *titALab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH/2*i, 35*displaywidth, SCREEN_WIDTH/2, 20*displaywidth) Font:15.0 Text:@"" Color:RGB(238, 103, 94)];
        titALab.textAlignment = NSTextAlignmentCenter;
        [topView addSubview:titALab];
        if (i == 0)
        {
            _orderLab = titALab;
        }
        else
        {
            _scoringLab = titALab;
        }
        UIButton *closeBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH/2*i, 0, SCREEN_WIDTH/2, 75*displaywidth) ImageName:nil Target:self Action:@selector(closeJobTypeAction:) Title:nil Font:12.0];
        closeBtn.tag = 10+i;
        closeBtn.backgroundColor = [UIColor clearColor];
        [topView addSubview:closeBtn];
    }
    CGFloat height = SCREEN_HEIGHT-STA_NAV_HEIGHT-60*displaywidth-SCREER_HeiX;
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 60*displaywidth, SCREEN_WIDTH, height)];
    _scrollView.delegate = self;
    _scrollView.backgroundColor = BacksColor;
    _scrollView.contentOffset = CGPointMake(0, 0);
    _scrollView.pagingEnabled = NO;
    _scrollView.bounces = NO;
    _scrollView.showsHorizontalScrollIndicator = YES;
    _scrollView.contentSize = CGSizeMake(SCREEN_WIDTH*2, height);
    _scrollView.scrollEnabled = NO;
    [self.view addSubview:_scrollView];
    
    self.leftTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height) style:UITableViewStylePlain];
    _leftTableview.backgroundColor = BacksColor;
    _leftTableview.delegate = self;
    _leftTableview.dataSource = self;
    _leftTableview.tag = 20;
    [_leftTableview setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    [_scrollView addSubview:_leftTableview];
    self.rightTableview = [[UITableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, height) style:UITableViewStylePlain];
    _rightTableview.backgroundColor = BacksColor;
    _rightTableview.delegate = self;
    _rightTableview.dataSource = self;
    _rightTableview.tag = 22;
    [_rightTableview setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    [_scrollView addSubview:_rightTableview];
    
    self.leftTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.leftTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.leftTableview.mj_footer.automaticallyHidden = YES;
    self.leftTableview.estimatedRowHeight = 0;
    self.leftTableview.estimatedSectionHeaderHeight = 0;
    self.leftTableview.estimatedSectionFooterHeight = 0;
    
    self.rightTableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.rightTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.rightTableview.mj_footer.automaticallyHidden = YES;
    self.rightTableview.estimatedRowHeight = 0;
    self.rightTableview.estimatedSectionHeaderHeight = 0;
    self.rightTableview.estimatedSectionFooterHeight = 0;
    
}

- (void)loadNewHeaderData
{
    if (_closeType == 0)
    {
        _leftPage = 0;
        [self requestProjectList:_leftPage];
    }
    else
    {
        _rightPage = 0;
        [self requestEvaluateList:_rightPage];
    }
    
}

- (void)loadMoreFootData
{
    if (_closeType == 0)
    {
        _leftPage ++;
        [self requestProjectList:_leftPage];
    }
    else
    {
        _rightPage ++;
        [self requestEvaluateList:_rightPage];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == 20)
    {
        return _orderAry.count;
    }
    else
    {
        return _scoringAry.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        NSString *cellpath = leftCellPath;
        if (tableView.tag == 22)
        {
            cellpath = rightCellPath;
        }
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellpath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (tableView.tag == 20)
    {
        cell.backgroundColor = BacksColor;
        UIView *whiteview = [[UIView alloc] initWithFrame:CGRectMake(5*displaywidth, 5*displaywidth, SCREEN_WIDTH-10*displaywidth, 125*displaywidth)];
        whiteview.backgroundColor = [UIColor whiteColor];
        whiteview.layer.cornerRadius = 5;
        whiteview.layer.masksToBounds = YES;
        [cell.contentView addSubview:whiteview];
        if (_orderAry.count > 0)
        {
            JobsModel *model = _orderAry[indexPath.row];
            UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 15*displaywidth, SCREEN_WIDTH-80*displaywidth, 25*displaywidth) Font:16.0 Text:model.name Color:RGB(129, 148, 196)];
            [whiteview addSubview:nameLab];
            UILabel *tostLab = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 40*displaywidth, SCREEN_WIDTH-80*displaywidth, 50*displaywidth) Font:13.0 Text:[NSString stringWithFormat:@"生产说明：\n%@",model.remark] Color:RGB(77, 77, 77)];
            tostLab.lineBreakMode = NSLineBreakByTruncatingTail;
            tostLab.adjustsFontSizeToFitWidth = NO;
            [whiteview addSubview:tostLab];
            UILabel *timeLab = [ZCControl createLabelWithFrame:CGRectMake(20*displaywidth, 90*displaywidth, SCREEN_WIDTH-120*displaywidth, 20*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@"项目工期：%@至%@",model.startDate,model.endDate] Color:RGB(128, 128, 128)];
            [whiteview addSubview:timeLab];
            UIButton *detailBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-125*displaywidth, 90*displaywidth, 100*displaywidth, 20*displaywidth) ImageName:nil Target:self Action:@selector(detailAction:) Title:@"查看详情" Font:13.0];
            detailBtn.backgroundColor = [UIColor whiteColor];
            detailBtn.tag = 100+indexPath.row;
            [detailBtn setTitleColor:RGB(236, 165, 84) forState:UIControlStateNormal];
            detailBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            detailBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            [whiteview addSubview:detailBtn];
            NSInteger statusNum = [model.status integerValue];
            UIImageView *typeImgView = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-45*displaywidth, 5*displaywidth, 40*displaywidth, 35*displaywidth) ImageName:@"jinxingzhong"];
            typeImgView.contentMode = UIViewContentModeScaleAspectFit;
            typeImgView.hidden = YES;
            [cell.contentView addSubview:typeImgView];
            if (statusNum == 2)
            {
                typeImgView.hidden = NO;
            }
            if (statusNum == 3)
            {
                typeImgView.hidden = NO;
                typeImgView.frame = CGRectMake(SCREEN_WIDTH-60*displaywidth, 35*displaywidth, 45*displaywidth, 45*displaywidth);
                typeImgView.image = [UIImage imageNamed:@"yiwancheng"];
            }
            if (statusNum == 1 || statusNum == 4 || statusNum == 0)
            {
                typeImgView.hidden = NO;
                typeImgView.frame = CGRectMake(SCREEN_WIDTH-60*displaywidth, 35*displaywidth, 45*displaywidth, 45*displaywidth);
                typeImgView.image = [UIImage imageNamed:@"daiqueren"];
            }
        }
       
    }
    else
    {
        if (_scoringAry.count > 0)
        {
            ScoringModel *model = _scoringAry[indexPath.row];
            UIView *lineBview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1*displaywidth)];
            lineBview.backgroundColor = LinesColor;
            [cell.contentView addSubview:lineBview];
            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(10*displaywidth, 15*displaywidth, 40*displaywidth, 40*displaywidth) ImageName:@"toux"];
            imgView.layer.cornerRadius = 20*displaywidth;
            imgView.layer.masksToBounds = YES;
            if (model.user.headImg.length > 0)
            {
                [imgView sd_setImageWithURL:[NSURL URLWithString:model.user.headImg] placeholderImage:[UIImage imageNamed:@"toux"]];
            }
            [cell.contentView addSubview:imgView];
            NSInteger typeNum = [model.user.type integerValue];
            NSString *typeName = @"雇主";
            UIColor *backColor = RGB(238, 103, 94);
            if (typeNum == 2)
            {
                typeName = @"承包人";
                backColor = ThemeColor;
            }
            if (typeNum == 3)
            {
                typeName = @"工人";
                backColor = ThemeColor;
            }
            UILabel *typrLab = [ZCControl createLabelWithFrame:CGRectMake(60*displaywidth, 15*displaywidth, 30*displaywidth, 15*displaywidth) Font:10.0 Text:typeName Color:[UIColor whiteColor]];
            typrLab.backgroundColor = backColor;
            typrLab.textAlignment = NSTextAlignmentCenter;
            typrLab.layer.cornerRadius = 2;
            typrLab.layer.masksToBounds = YES;
            [cell.contentView addSubview:typrLab];
            
            UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(105*displaywidth, 10*displaywidth, SCREEN_WIDTH-215*displaywidth, 25*displaywidth) Font:12.0 Text:model.user.name Color:RGB(153, 153, 153)];
            [cell.contentView addSubview:nameLab];
            
            UILabel *contenLab = [ZCControl createLabelWithFrame:CGRectMake(105*displaywidth, 35*displaywidth, SCREEN_WIDTH-120*displaywidth, 35*displaywidth) Font:14.0 Text:model.user.name Color:RGB(77, 77, 77)];
            [cell.contentView addSubview:contenLab];
            
            CDZStarsControl *starsControl = [CDZStarsControl.alloc initWithFrame:CGRectMake(SCREEN_WIDTH-110*displaywidth, 10*displayheight, 100*displaywidth , 25*displayheight) stars:5 starSize:CGSizeMake(20*displayheight, 20*displayheight) noramlStarImage:[UIImage imageNamed:@"huixx"] highlightedStarImage:[UIImage imageNamed:@"hongxx"]];
            starsControl.delegate = self;
            starsControl.allowFraction = YES;
            starsControl.score = [model.grade floatValue];
            [cell.contentView addSubview:starsControl];
            
        }
        
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 22) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请选择举报理由" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        [alertVC addAction:[UIAlertAction actionWithTitle:@"低俗脏话" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            FeedBackViewController *vc = [[FeedBackViewController alloc] init];
            vc.titleStr = @"举报";
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        
        [alertVC addAction:[UIAlertAction actionWithTitle:@"营销诈骗" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            FeedBackViewController *vc = [[FeedBackViewController alloc] init];
            vc.titleStr = @"举报";
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"其他理由" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            FeedBackViewController *vc = [[FeedBackViewController alloc] init];
            vc.titleStr = @"举报";
            [self.navigationController pushViewController:vc animated:YES];
        }]];
        
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        
        
        [self presentViewController:alertVC animated:YES completion:nil];
    } else if (tableView.tag == 20) {
        JobsModel *model = _orderAry[indexPath.row];
        JobDetailViewController *jobDetailVC = [[JobDetailViewController alloc] init];
        jobDetailVC.ID = model.ID;
        if ([model.status integerValue] == 1 || [model.status integerValue] == 0) {
            jobDetailVC.detailType = RECOMMENDTYPE;
            [self.navigationController pushViewController:jobDetailVC animated:YES];
        } else if ([model.status integerValue] == 2) {
            jobDetailVC.detailType = CHECKTYPE;
            [self.navigationController pushViewController:jobDetailVC animated:YES];
        } else if ([model.status integerValue] == 3) {
            jobDetailVC.detailType = EVALUATETYPE;
            [self.navigationController pushViewController:jobDetailVC animated:YES];
        } else if ([model.status integerValue] == 4) {
            jobDetailVC.detailType = RECOMMENDTYPE;
            [self.navigationController pushViewController:jobDetailVC animated:YES];
        }
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 20)
    {
        return 130*displaywidth;
    }
    return 70*displaywidth;
}



//查看详情
- (void)detailAction:(UIButton *)btn
{
    NSInteger index = btn.tag-100;
    JobsModel *model = _orderAry[index];
    JobDetailViewController *jobDetailVC = [[JobDetailViewController alloc] init];
    jobDetailVC.ID = model.ID;
    if ([model.status integerValue] == 1 || [model.status integerValue] == 0) {
        jobDetailVC.detailType = RECOMMENDTYPE;
        [self.navigationController pushViewController:jobDetailVC animated:YES];
    } else if ([model.status integerValue] == 2) {
        jobDetailVC.detailType = CHECKTYPE;
        [self.navigationController pushViewController:jobDetailVC animated:YES];
    } else if ([model.status integerValue] == 3) {
        jobDetailVC.detailType = EVALUATETYPE;
        [self.navigationController pushViewController:jobDetailVC animated:YES];
    } else if ([model.status integerValue] == 4) {
        jobDetailVC.detailType = RECOMMENDTYPE;
        [self.navigationController pushViewController:jobDetailVC animated:YES];
    }
}




- (void)closeJobTypeAction:(UIButton *)btn
{
    _closeType = btn.tag-10;
    if (btn.tag == 10)
    {
        //项目订单
        [_scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        
    }
    else
    {
        //评价分数
        [_scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:YES];

    }
}

- (void)requestProjectList:(NSInteger)page
{
    WEAKSELF;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%ld",page]};
    [HYBaseHandler requestProjectListParmers:dic Success:^(id obj) {
        [weakSelf.leftTableview.mj_header endRefreshing];
        [weakSelf.leftTableview.mj_footer endRefreshing];
        if ([obj server_Getcodecheck])
        {
            NSArray *orderArray = [JobsModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakSelf.leftPage == 0)
                {
                    [weakSelf.orderAry removeAllObjects];
                }
                [weakSelf.orderAry addObjectsFromArray:orderArray];
                NSString *orderNumStr = obj[@"data"][@"numberOfElements"];
                weakSelf.orderLab.text = [NSString stringWithFormat:@"%@",orderNumStr];
                double scoringD = [obj[@"grade"] doubleValue];
                weakSelf.scoringLab.text = [NSString stringWithFormat:@"%.1lf",scoringD];
                [weakSelf.leftTableview reloadData];
            });
            
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.leftTableview.mj_header endRefreshing];
        [weakSelf.leftTableview.mj_footer endRefreshing];
    }];
}

- (void)requestEvaluateList:(NSInteger)page
{
    WEAKSELF;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%ld",page],
                          @"target.id":[LTools cacheForKey:SERVER_UserID]};
    [HYBaseHandler requestEvaluateListParmers:dic Success:^(id obj) {
        [weakSelf.rightTableview.mj_header endRefreshing];
        [weakSelf.rightTableview.mj_footer endRefreshing];
        if ([obj server_Getcodecheck])
        {
            NSArray *scoringArray = [ScoringModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (weakSelf.rightPage == 0)
                {
                    [weakSelf.scoringAry removeAllObjects];
                }
                [weakSelf.scoringAry addObjectsFromArray:scoringArray];
        
                [weakSelf.rightTableview reloadData];
            });
            
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.rightTableview.mj_header endRefreshing];
        [weakSelf.rightTableview.mj_footer endRefreshing];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
